from universal.common_header import *
print('root_path1')
from Module.xRayDetection.xray.logs import Logger
print('root_path2')

def dir_root():
    if getattr(sys, 'frozen', False):
        absPath = os.path.dirname(os.path.abspath(sys.executable))
    elif __file__:
        absPath = os.path.dirname(os.path.abspath(__file__))
        absPath = absPath.split(f'{os.sep}universal')[0]
    return absPath


def MK_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

def MK_init_dir(path_dir,className):
    NG_Path = os.path.join(path_dir, className)
    os.makedirs(NG_Path)
    return NG_Path

def TextBrowserNews(BoxMessages, news=None):
    BoxMessages.append(news)
    BoxMessages.moveCursor(BoxMessages.textCursor().StartOfLine)
    BoxMessages.moveCursor(BoxMessages.textCursor().Down)

def drawDetectBox(img,Box_list):
    for box in Box_list:
        x1 = int(box[0])
        y1 = int(box[1])
        x2 = int(box[2])
        y2 = int(box[3])
        conf = round(box[4], 3)
        cls = box[6] if len(box) > 6 else box[5]
        conf_cls = '%s %s' % ("baodian", conf)
        cv2.rectangle(img, (x1, y1), (x2, y2), (255, 55, 55), thickness=2)
        cv2.putText(img, conf_cls, (x1, y1),
                    cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 255, 0), thickness=2)
    return img

def init_log():
    logPath = dir_root() + os.sep + 'logs'
    if not os.path.exists(logPath):
        os.mkdir(logPath)
    logger = Logger(logPath)
    logger.log(Logger.INFO, 'init_log')
    return logger

def cvimg_to_qtimg(cvimg,flag = False):
    cvimg = cvimg.astype(np.uint8)
    shape = cvimg.shape
    if cvimg.ndim == 4:
        qimg = cv2.cvtColor(cvimg, cv2.COLOR_RGB2RGBA)
        qimg = QImage(qimg.data, shape[1], shape[0], shape[1] * 4, QImage.Format_RGB32)
    elif cvimg.ndim == 3:
        if flag:
            cvimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB)
        qimg = QImage(cvimg.data, shape[1], shape[0],  shape[1] * 3,QImage.Format_RGB888)
    elif cvimg.ndim == 2:
        qimg = QImage(cvimg.data, shape[1], shape[0], shape[1] * 1, QImage.Format_Grayscale8)
    return qimg


def news_box(add_str):
    customMsgBox = QMessageBox()
    customMsgBox.setFont(QFont(FONTSTR, FONT_SIZE1))
    customMsgBox.setWindowTitle("News")
    cancelButton = customMsgBox.addButton("Cancel", QMessageBox.ActionRole)
    OKButton = customMsgBox.addButton("OK", QMessageBox.ActionRole)
    # cancelButton.setStyleSheet(
    #     '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')  # rgb(170,200,50)
    # OKButton.setStyleSheet(
    #     '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')  # rgb(170,200,50)
    customMsgBox.setText(add_str)
    customMsgBox.exec_()
    return customMsgBox,cancelButton,OKButton

def news_box2(add_str):
    customMsgBox = QMessageBox()
    customMsgBox.setFont(QFont(FONTSTR, FONT_SIZE1))
    customMsgBox.setWindowTitle("News")
    cancelButton = customMsgBox.addButton("ok", QMessageBox.ActionRole)
    # cancelButton.setStyleSheet(
    #     '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')  # rgb(170,200,50)
    customMsgBox.setText(add_str)
    customMsgBox.exec_()
    return customMsgBox,cancelButton

def drawBox(jpgfile,resultDir,xmlfile):
    imgName = os.path.basename(jpgfile)
    finalfile = resultDir + os.sep + imgName

    # 打开xml文档
    DOMTree = xml.dom.minidom.parse(xmlfile)
    # 得到文档元素对象
    collection = DOMTree.documentElement
    # 读取图片
    img = cv2.imread(jpgfile)

    filenamelist = collection.getElementsByTagName("filename")
    filename = filenamelist[0].childNodes[0].data
    # print(filename)
    # 得到标签名为object的信息
    objectlist = collection.getElementsByTagName("object")

    for objects in objectlist:
        # 每个object中得到子标签名为name的信息
        namelist = objects.getElementsByTagName('name')
        # 通过此语句得到具体的某个name的值
        objectname = namelist[0].childNodes[0].data

        bndbox = objects.getElementsByTagName('bndbox')
        for box in bndbox:
            x1_list = box.getElementsByTagName('xmin')
            x1 = int(float(x1_list[0].childNodes[0].data))
            y1_list = box.getElementsByTagName('ymin')
            y1 = int(float(y1_list[0].childNodes[0].data))
            x2_list = box.getElementsByTagName('xmax')
            x2 = int(float(x2_list[0].childNodes[0].data))
            y2_list = box.getElementsByTagName('ymax')
            y2 = int(float(y2_list[0].childNodes[0].data))
            cv2.rectangle(img, (x1, y1), (x2, y2), (255, 55, 55), thickness=2)
            cv2.putText(img, objectname, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 255, 0),
                       thickness=2)
            cv2.imwrite('%s' % finalfile, img)

def get_img_list(dir, firelist, ext=None):
    newdir = dir
    if os.path.isfile(dir):  # 如果是文件
        if ext is None:
            firelist.append(dir)
        else:
            for i in ext:
                if i in dir[-4:]:
                    firelist.append(dir)
    elif os.path.isdir(dir):  # 如果是目录
        for s in os.listdir(dir):
            newdir = os.path.join(dir, s)
            get_img_list(newdir, firelist, ext)
    return firelist


def drawDetectBox(Img,Box_list,savePath):
    height = Img.shape[0]
    width = Img.shape[1]
    if len(Box_list) < 1:
        cv2.putText(Img, "OK", (int(width - width / 6),
                                int(height / 6)), cv2.FONT_HERSHEY_PLAIN, 2.0,
                    (0, 255, 0), 2)
    else:
        for box in Box_list:
            x1 = box[0]
            y1 = box[1]
            x2 = box[2]
            y2 = box[3]
            conf = round(box[4], 3)
            cls = box[6]
            conf_cls = '%s %s' % (cls, conf)
            cv2.rectangle(Img, (x1, y1), (x2, y2), (255, 55, 55), thickness=2)
            cv2.putText(Img, conf_cls, (x1, y1),
                        cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 255, 0), thickness=2)
    if savePath!=None:
        cv2.imwrite(savePath, Img)

def drawDetectBox_NoCls(Img,Box_list,savePath):  #没有分类模型的信息用这个画框
    height = Img.shape[0]
    width = Img.shape[1]
    if len(Box_list) < 1:
        cv2.putText(Img, "OK", (int(width - width / 6),
                                int(height / 6)), cv2.FONT_HERSHEY_PLAIN, 2.0,
                    (0, 255, 0), 2)
    else:
        for box in Box_list:
            x1 = int(box[0])
            y1 = int(box[1])
            x2 = int(box[2])
            y2 = int(box[3])
            conf = round(box[4], 3)
            cls = box[5]
            conf_cls = '%s %s' % (cls, conf)
            cv2.rectangle(Img, (x1, y1), (x2, y2), (255, 55, 55), thickness=2)
            cv2.putText(Img, conf_cls, (x1, y1),
                        cv2.FONT_HERSHEY_COMPLEX, 1.0, (0, 255, 0), thickness=2)
    if savePath != None:
        cv2.imwrite(savePath, Img)

def scanAllImages(folderPath, extensions_=[]):
    extensions = ['.%s' % fmt.data().decode("ascii").lower() for fmt in QImageReader.supportedImageFormats()]
    extensions += extensions_
    images = []
    for root, dirs, files in os.walk(folderPath):
        for file in files:
            if file.lower().endswith(tuple(extensions)):
                relativePath = os.path.join(root, file)
                path = ustr(os.path.abspath(relativePath))
                images.append(path)
    images.sort(key=lambda x: x.lower())
    return images

def read(filename, default=None):
    try:
        with open(filename, 'rb') as f:
            return f.read()
    except:
        return default

# def currentPath(self):
#      return os.path.dirname(self.filePath) if self.filePath else '.'
#   def saveFile(self, _value=False):  #
#     if self.labelImgsPath is not None and len(ustr(self.labelImgsPath)):
#         if self.filePath:
#             savedFileName = os.path.splitext(self.filePath)[0]
#             self._saveFile(savedFileName)
#     else:
#         imgFileDir = os.path.dirname(self.filePath)
#         imgFileName = os.path.basename(self.filePath)
#         savedFileName = os.path.splitext(imgFileName)[0]
#         savedPath = os.path.join(imgFileDir, savedFileName)
#         openDialogPath = self.currentPath()
#         self._saveFile(savedPath if self.labelFile
#                        else saveFileDialog(openDialogPath, self.filePath))